package db

import (
	"asuOfficialApi/config"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/pelletier/go-toml"
	"sync"
)

var mysqlInstance *xorm.Engine
var mysqlOnce sync.Once

var (
	DB = newDB()
)

func newDB() *xorm.Engine {
	mysqlOnce.Do(func() {
		driver := config.Conf.Get("database.driver").(string)
		c := config.Conf.Get(driver).(*toml.Tree)

		sourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
			c.Get("username").(string),
			c.Get("password").(string),
			c.Get("host").(string),
			c.Get("port").(int64),
			c.Get("database").(string))

		engine, err := xorm.NewEngine(driver, sourceName)
		if err != nil {
			//log.Fatal("db NewEngine error ", err.Error())
			panic("db NewEngine error " + err.Error())
			return
		}

		engine.ShowSQL(true)
		mysqlInstance = engine
	})

	return mysqlInstance
}
